<template>
  <a-modal
    :open="open"
    width="640px"
    :title="rowData?.jhdh ? '修改采购计划' : '新增采购计划'"
    centered
    :ok-button-props="{ disabled: !isCompleted }"
    ok-text="保存"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form :model="formState" class="form-style-flex">
      <a-form-item label="制单人" class="w-full">
        {{ formState.jhr }}
      </a-form-item>
      <a-form-item label="计划日期" v-bind="validateInfos.jhrq" class="w-1/2">
        <a-date-picker v-model:value="formState.jhrq" class="w-full" placeholder="计划日期" :allow-clear="false" value-format="YYYY-MM-DD" />
      </a-form-item>
      <!-- <a-form-item label="类别" class="w-1/2">
        <a-radio-group v-model:value="formState.djlb">
          <a-radio value="0">药材</a-radio>
          <a-radio value="1">物资</a-radio>
        </a-radio-group>
      </a-form-item> -->
      <a-form-item label="供应商" v-bind="validateInfos.gysmc" class="w-full">
        <SelectTable v-model:value="formState.gysmc" type="物资供应商" @select="onSelectSupplier" />
      </a-form-item>
      <a-form-item label="备注" class="w-full">
        <a-textarea v-model:value="formState.cmemo" :rows="3" placeholder="请输入" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import useUserStore from '@/store/user'
import { post } from '@/utils/request'

const router = useRouter()

const emit = defineEmits(['update:open', 'ok'])
const { empName } = useUserStore()
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const formState = ref({
  // djlb: '0',
  jhr: empName,
  gysmc: '',
  cmemo: '',
  jhrq: dayjs().format('YYYY-MM-DD HH:mm:ss')
})
const rulesState = ref({
  gysmc: [{ required: true, message: '请选择供应商' }],
  jhrq: [{ required: true, message: '请选择计划日期' }]
})
const { isCompleted, resetFields, validate, validateInfos } = useForm(formState, rulesState)

watch(
  () => props.open,
  (val) => {
    if (val && props.rowData?.jhdh) {
      formState.value = props.rowData
    }
  }
)
const onCancel = () => {
  emit('update:open', false)
  resetFields()
}
const onOk = async () => {
  await validate()
  const { code, msg, data } = await post('/materials/psiform/doSaveSupplyPlanHead', formState.value)
  if (code === 0) {
    message.success('保存成功')
    onCancel()
    emit('ok')
    router.push({
      path: '/material/warehouse/plan-detail',
      query: {
        jhdh: data.jhdh
      }
    })
  } else {
    message.error(msg)
  }
}
const onSelectSupplier = (supplier) => {
  formState.value.gysbh = supplier?.gysbh
  formState.value.gysmc = supplier?.gysmc
}
</script>
